import requests
import json
from util.operation_json import OperationJson
from base.runmethod import RunMethod


class OperationHeader:

    def __init__(self):
        self.la = RunMethod()
        self.op_json = OperationJson("../dataconfig/header.json")

    def get_response_token(self, response):
        """ 获取登录返回的token """
        re = json.loads(response)
        token = re["token"]
        return token

    def get_response_cookie(self, method, url, request_data):
        """ 获取登录返回的cookie """
        p = self.la.get_is_post(method, url, request_data).cookies
        cookies = requests.utils.dict_from_cookiejar(p)
        cookie = json.dumps(cookies)
        # c = cookie.replace("{", "").replace("}", "").replace(': ', "=").replace('"', "").replace(",", ";")
        return cookie

    def write_headers(self, cookie=None, token=None):
        """ 将token和cookie写入请求头 """
        headers_data = self.op_json.read_data()
        headers_data["cookie"] = cookie
        headers_data["Authorization"] = "B " + token
        self.op_json.write_data(headers_data)
